package com.mvc.business.user.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.mvc.vo.User;
/**
 * @author HK
 * 实现权限拦劫
 *springAnnotation-hibernate.xml中配置mvc拦劫器
 */
@Component
public class AuthIntercepter extends HandlerInterceptorAdapter{
	
	/**
	 * 在执行action里面的处理逻辑之前执行，它返回的是boolean，
	 * 这里如果我们返回true在接着执行postHandle和afterCompletion，如果我们返回false则中断执行。
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("perHandle+++++++++++++++++++++");
		//实现权限验证
		User u = (User)request.getSession().getAttribute("user");
		//当用户没有登陆，模拟登陆
		if (null == u) {
			System.out.println("当前无用户登陆，自动登陆测试用户");
			request.getSession().setAttribute("user",new User("1", "测试用户", "123", 11, "男"));
			return true;//false时使用response.sendRedirect("");跳转到权限登陆页面 
		}
		//用户已登陆，正常执行请求 ,不拦劫
		else{
			System.out.println("当前登陆用户:"+u.getUserName());
			return true;
		}
	}
	
	/**
	 * 在执行action里面的逻辑后返回视图之前执行。
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
		//System.out.println("postHandle+++++++++++++++++++++");
		super.postHandle(request, response, handler, modelAndView);
	}
	
	/**
	 * 在action返回视图后执行。
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		
		//System.out.println("afterCompletion+++++++++++++++++++++");
		super.afterCompletion(request, response, handler, ex);
	}	
}
